package team.nmsg.ge.system.dao.impl;

import java.util.ArrayList;
import java.util.Set;

import org.hibernate.SQLQuery;
import org.hibernate.Session;





import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import team.nmsg.ge.system.bean.SysOper;
import team.nmsg.ge.system.bean.SysRole;
import team.nmsg.ge.system.dao.ISysUserRoleDao;

@Component
public class ISysUserRoleDaoImpl extends NMSDaoSupport implements ISysUserRoleDao{
	private static Logger logger =  LoggerFactory.getLogger(  ISysUserRoleDaoImpl.class );
	
	@Override
	public boolean updModifyOperToRole(int roleId, String[] operId) {
		Session hSession = getHSession();
		try {
			ArrayList<String> insertoper = new ArrayList();
			ArrayList<String> deleteoper=new ArrayList();
			ArrayList<String> oldoper=new ArrayList();
			ArrayList<String> newoper=new ArrayList();
			SysRole role = (SysRole) hSession.get(SysRole.class, roleId);
			Set<SysOper> tempoper=role.getOpers();
			if(operId!=null){
				int length=operId.length;
				for(int i=0;i<length;i++){
					newoper.add(operId[i]);
				}
			}
			for( SysOper o : tempoper){
				String tempid=String.valueOf(o.getOperId());
			    oldoper.add( tempid);
			    if(newoper.indexOf(tempid)==-1){      //旧权限在新权限中不存在
			    	 deleteoper.add(tempid);  //加入删除列表
			    }
			}
			if(operId!=null){
				int length2=operId.length;
				for(int i=0;i<length2;i++){
				if(oldoper.indexOf(operId[i])==-1){ //新权限在旧权限不存在
					insertoper.add(operId[i]);//加入插入列表
				}
			}
			}
			int insertsize=insertoper.size();
			int deletesize=deleteoper.size();
			if(insertsize>0){
				StringBuilder insertSql=new StringBuilder( "insert into sys_r_o values ");
				for(int i=0;i<insertsize;i++){
					if(i+1!=insertsize)
						insertSql.append("("+roleId+","+insertoper.get(i)+"),");
					else
						insertSql.append("("+roleId+","+insertoper.get(i)+")");
				}
				SQLQuery  hSqlQuery = hSession.createSQLQuery( insertSql.toString() );
				hSqlQuery.executeUpdate();
			}
			if(deletesize>0){
				StringBuilder deleteSql=new StringBuilder( "delete from sys_r_o where r_id= "+roleId+" and (");
				for(int i=0;i<deletesize;i++){
					if(i+1!=deletesize)
						deleteSql.append(" o_id= "+deleteoper.get(i)+" or ");
					else
						deleteSql.append(" o_id= "+deleteoper.get(i)+" ) ");
				}
				SQLQuery  hSqlQuery2 = hSession.createSQLQuery( deleteSql.toString() );
				hSqlQuery2.executeUpdate();
			}
			
			

		}catch (Exception e) {
			logger.error("",e);
			return false;
		}
		return true;  
	}
}
